package com.mindmap.model;

import java.awt.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class MindMap implements Serializable {
    private static final long serialVersionUID = 1L;
    private Node root;
    private String title;
    private transient Node selectedNode;

    public MindMap() {
        this.title = "未命名思维导图";
    }

    public Node getRoot() {
        return root;
    }

    public void setRoot(Node root) {
        this.root = root;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Node getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(Node selectedNode) {
        if (this.selectedNode != null) {
            this.selectedNode.setSelected(false);
        }
        this.selectedNode = selectedNode;
        if (selectedNode != null) {
            selectedNode.setSelected(true);
        }
    }

    public List<Node> getAllNodes() {
        List<Node> nodes = new ArrayList<>();
        if (root != null) {
            nodes.add(root);
            addChildrenNodes(root, nodes);
        }
        return nodes;
    }

    private void addChildrenNodes(Node parent, List<Node> nodes) {
        for (Node child : parent.getChildren()) {
            nodes.add(child);
            addChildrenNodes(child, nodes);
        }
    }

    public Node findNodeAt(Point point) {
        return findNodeAt(root, point);
    }

    private Node findNodeAt(Node node, Point point) {
        if (node == null) return null;
        if (node.contains(point)) return node;

        for (Node child : node.getChildren()) {
            Node found = findNodeAt(child, point);
            if (found != null) return found;
        }

        return null;
    }
}
